package com.java.controller;

import com.java.model.GeoIPInfo;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;

@RestController
public class GeoIpController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private DatabaseReader reader;

	// http://localhost:8088/update/GeoIp

    /**
     * form-data请求参数 key=ip,vlaue={要查询的ip}
     * @param request
     * @return
     * @throws Exception
     */
	@RequestMapping(value = "/update/GeoIp",method = RequestMethod.POST)
	@ResponseBody
	public String GeoIp(HttpServletRequest request) throws Exception{
        String ip1 = request.getParameter("ip");
        logger.info("ip:{}", ip1);
        if(ip1!=null)
		    return getCityByIP(ip1).toString();
        else
            return "Can not be empty!";
	}

    /**
     * 含有多个小数点的参数时丢失数据，有两种解决办法{ip}改{ip:.+}，或者{ip}追加{ip}/get(任意后缀)
     * ps：传参多加一个“.”也行，哈哈
     * 可以查看博客 https://blog.csdn.net/jrainbow/article/details/46126179
     * @param ip
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update/GeoIp/{ip:.+}",method = RequestMethod.GET)
    @ResponseBody
    public String getGeoIp(@PathVariable("ip") String ip) throws Exception{
        logger.info("ip:{}", ip);
        if(ip!=null)
            return getCityByIP(ip).toString();
        else
            return "Can not be empty!";
    }

	public GeoIPInfo getCityByIP(String ip) throws Exception { // 创建 GeoLite2
		InetAddress ipAddress = InetAddress.getByName(ip);
		// 获取查询结果
		CityResponse response = reader.city(ipAddress);
		GeoIPInfo geoIPInfo=new GeoIPInfo();
        geoIPInfo.setIp(ip);
		// 获取国家信息
		String country = response.getCountry().getNames().get("zh-CN");
		geoIPInfo.setCountry(country);
		logger.info("国家:{}", country);
		// 获取省份
		String subdivision = response.getMostSpecificSubdivision().getNames().get("en");
		geoIPInfo.setSubdivision(subdivision);
		logger.info("省份:{}", subdivision);
		// 城市
		String city = response.getCity().getName();
		geoIPInfo.setCity(city);
		logger.info("城市:{}:{}",response.getCity(), city);
		// 获取城市
		String latitude = response.getLocation().getLatitude().toString();
		String longitude = response.getLocation().getLongitude().toString();
		geoIPInfo.setLatitude(latitude);
		geoIPInfo.setLongitude(longitude);
		logger.info("经度:{}", latitude);
		logger.info("纬度:{}", longitude);


		logger.info("geoIPInfo:{}",geoIPInfo);
		return geoIPInfo;
	}
}
